/**
 * @file models/retail.js
 * @author
 */
import { routerRedux } from 'dva/router';
import api from '../api';
import moment from 'moment';
import _ from 'lodash';


export default {
	namespace: 'retail',
	state: {

	},
	subscriptions : {
		setup({dispatch, history}) {
			history.listen(({ pathname, query }) => {
				// 没有参数时，向后端请求数据，并且改变query
				if( pathname === '/retail' ){
					dispatch({type: 'whetherRequest',payload:query,pathname})
				}
			})
		}
	},
	effects : {

		* whetherRequest({
				payload,pathname
			}, { put,select}) {
				yield put({
					type: 'query',
					payload
				})
		},
		* query({payload}, {call, put,select}){
			const {
				trader=''
			}=payload
			if(trader){
				// 首先获取基础数据
				const [
					traderFeatures, //基础信息
          fdtScoreResponse, // fdtScore
          profitabilityResponse, // profitability
          riskControlResponse, // riskControl
          activityResponse, // activity
          consistencyResponse, // consistency
				]=yield [
					call(api.retail.getTraderFeatures,{
						trader
					}),
					call(api.retail.getFdtScore,{
						trader
					}),
					call(api.retail.getProfitability,{
						trader
					}),
					call(api.retail.getRiskControl,{
						trader
					}),
					call(api.retail.getActivity,{
						trader
					}),
					call(api.retail.getConsistency,{
						trader
					}),
				]
				if(traderFeatures.data){
					const [
						specialTradings,//记录信息
						trend,
						notesConfig,
            recommendationsAll
					]=yield [
						call(api.getRetailSpecialTradings,{
							trader
						}),
						call(api.getRetailHistoryAccountDailies,{
							trader
						}),
						call(api.getRetailCommentConfig),
						call(api.retail.getRecommendationsAll,{
							trader
						})
					]


					const datas=specialTradings&&specialTradings.length&&specialTradings.map((item)=>{
						const timesArr=[]

            if (_.isArray(item.closeOrder.closedPositionList) && item.closeOrder.closedPositionList.length > 0) {
              item.closeOrder.closedPositionList.map(item=>{
                timesArr.push(item.closeTime)
                timesArr.push(item.openTime)

              })
              timesArr.sort((a,b)=>a-b)
              
              return{
                openOrderId:item.openOrderId,
                closeOrderId:item.closeOrderId,
                from:moment(timesArr[0],'x').format('YYYYMMDD'),
                to:moment(timesArr[timesArr.length-1],'x').format('YYYYMMDD'),
              }
            } else {
              return {}
            }
						
					})||[]
					
					// 最大盈利的平仓记录
					const profitRecordDetail=specialTradings&&specialTradings.length&&specialTradings.find(item=>item.specialType==='max_profit')
					if(profitRecordDetail){
						yield put({
							type:'queryDetail',
							payload:{
								trader,
								openOrderId:profitRecordDetail.openOrderId,
								closeOrderId:profitRecordDetail.closeOrderId,
								stockCode:profitRecordDetail.closeOrder.symbol,
								from:profitRecordDetail.closeOrder.closedPositionList[0].openTime,
								to:profitRecordDetail.closeOrder.closedPositionList[0].closeTime,
							}
						})
					}

					// 最大亏损的平仓记录	
					const lossRecordDetail=specialTradings&&specialTradings.length&&specialTradings.find(item=>item.specialType==='max_loss')
					if(lossRecordDetail){
						yield put({
							type:'queryDetail',
							payload:{
								trader,
								openOrderId:lossRecordDetail.openOrderId,
								closeOrderId:lossRecordDetail.closeOrderId,
								stockCode:lossRecordDetail.closeOrder.symbol,
								from:lossRecordDetail.closeOrder.closedPositionList[0].openTime,
								to:lossRecordDetail.closeOrder.closedPositionList[0].closeTime,
							}
						})
					}

					// 最大盈利效率的平仓记录
					const pnlEfficiencyDetail=specialTradings&&specialTradings.length&&specialTradings.find(item=>item.specialType==='max_pnl_efficiency')
					if(pnlEfficiencyDetail){
						yield put({
							type:'queryDetail',
							payload:{
								trader,
								openOrderId:pnlEfficiencyDetail.openOrderId,
								closeOrderId:pnlEfficiencyDetail.closeOrderId,
								stockCode:pnlEfficiencyDetail.closeOrder.symbol,
								from:pnlEfficiencyDetail.closeOrder.closedPositionList[0].openTime,
								to:pnlEfficiencyDetail.closeOrder.closedPositionList[0].closeTime,
							}
						})
					}

					// 最大潜在风险的平仓记录
					const riskRecordDetail=specialTradings&&specialTradings.length&&specialTradings.find(item=>item.specialType==='max_potential_risk')
					if(riskRecordDetail){
						yield put({
							type:'queryDetail',
							payload:{
								trader,
								openOrderId:riskRecordDetail.openOrderId,
								closeOrderId:riskRecordDetail.closeOrderId,
								stockCode:riskRecordDetail.closeOrder.symbol,
								from:riskRecordDetail.closeOrder.closedPositionList[0].openTime,
								to:riskRecordDetail.closeOrder.closedPositionList[0].closeTime,
							}
						})
					}

					// 最大风险收益比的平仓记录
					const pnlRecordDetail=specialTradings&&specialTradings.length&&specialTradings.find(item=>item.specialType==='max_risk_over_pnl')
					if(pnlRecordDetail){
						yield put({
							type:'queryDetail',
							payload:{
								trader,
								openOrderId:pnlRecordDetail.openOrderId,
								closeOrderId:pnlRecordDetail.closeOrderId,
								stockCode:pnlRecordDetail.closeOrder.symbol,
								from:pnlRecordDetail.closeOrder.closedPositionList[0].openTime,
								to:pnlRecordDetail.closeOrder.closedPositionList[0].closeTime,
							}
						})
					}

					// 最大仓位效率的平仓记录
					const positionEfficiencyDetail=specialTradings&&specialTradings.length&&specialTradings.find(item=>item.specialType==='max_position_efficiency')
					if(positionEfficiencyDetail){
						yield put({
							type:'queryDetail',
							payload:{
								trader,
								openOrderId:positionEfficiencyDetail.openOrderId,
								closeOrderId:positionEfficiencyDetail.closeOrderId,
								stockCode:positionEfficiencyDetail.closeOrder.symbol,
								from:positionEfficiencyDetail.closeOrder.closedPositionList[0].openTime,
								to:positionEfficiencyDetail.closeOrder.closedPositionList[0].closeTime,
							}
						})
					}

					yield put({
						type: 'querySuccess',
						payload:{
							info:traderFeatures.data,
							notesConfig,
							trend:trend.data,
							details:specialTradings,
              recommendationsAll:recommendationsAll.data,
              fdtScore:fdtScoreResponse.data,
              profitability:profitabilityResponse.data,
              riskControl:riskControlResponse.data,
              activity:activityResponse.data,
              consistency:consistencyResponse.data,
						}
					})
				}else{
					yield put({
						type: 'querySuccess',
						payload:{
							msg:traderFeatures.msg
						}
					})
				}
			}

		},
		* queryDetail({payload}, {call,put,select}){

      let comment = '';
      try {
        comment =(yield call(api.retail.getCommentClosedPos,{
          trader:payload.trader,
          openOrderId:payload.openOrderId,
          closeOrderId:payload.closeOrderId
        })).data
      } catch (error) {
        
      }
			
			const dayNum = 0
			const dayDiff=moment(payload.to).diff(moment(payload.from), 'days')+1
			const kline = (yield call(dayDiff>dayNum?api.getSimpleDayKline:api.getSimpleMinKline, {
				stockCode:payload.stockCode,
				from:dayDiff>dayNum?moment(payload.from).subtract(20, 'days').format('YYYYMMDD'):moment(payload.from).format('YYYYMMDD093000'),
				to:dayDiff>dayNum?moment(payload.to).add(20, 'days').format('YYYYMMDD'):moment(payload.to).format('YYYYMMDD150000')
			})).data


			const state = yield select(state=>state.retail)
			const details=state.details
			details&&details.length&&details.map((item,i)=>{
				item.commentClosedPos=comment
				item.Kline=kline
			})
      
			yield put({
				type: 'querySuccess',
				payload:{
					details,
				}
			})
		},
		* putEducationFeed({payload}, {call}){
			yield call(api.retail[`${payload.action}Feedback`][payload.name], payload.educationId, payload.traderId)
		},
		* changeRouter({payload}, {put}){
			yield put(routerRedux.push(payload))
		},
    * gotoRetailEducationDetail({payload}, {put}){
      yield put(routerRedux.push({
        pathname: '/retailEducationDetail',
        query: {
          id: payload.id,
          trader: payload.trader,
        },
      }));
    }
	},
	reducers : {
		setState(state, {payload}) {
			return {
				...state,
				...payload
			}
		},

		clearState(state) {
			const {
				info,
				notesConfig,
				trend,
				details,
				...other
			}=state
      return{
				...other
			}
    },
		querySuccess(state, {payload}) {
			return {
				...state,
				...payload
			}
		}

	}
};
